package com.simen.connectandroid.command;

import com.simen.connectandroid.command.deviceinfo.*;
import com.simen.connectandroid.model.Device;
import com.simen.connectandroid.model.DeviceStatus;
import com.simen.hellobytes.log.Log;
import com.simen.hellobytes.runtime.RuntimeHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created on 2021/10/30 14:44.
 *
 * @author Simen
 */
public class DevicesCommand extends AdbCommand<DevicesCommand> {

    private static final String TAG = DevicesCommand.class.getSimpleName();
    private final List<Device> deviceList = new ArrayList<Device>();
    private boolean getDeviceInfo = true;

    @Override
    public DevicesCommand exec() {
        log = RuntimeHelper.create("adb devices").exec().getOutputLog();

        if (execResult()) {
            String[] lines = log.split("\n");
            if (lines.length > 1) {
                for (int i = 1; i < lines.length; i++) {
                    String[] params = RuntimeHelper.splitCommand(lines[i]);
                    if (params.length == 2) {
                        Device device = new Device(params[0], DeviceStatus.parse(params[1]));
                        if (getDeviceInfo) {
                            device.setBrand(new BrandCommand(device).exec().getResult());
                            device.setName(new NameCommand(device).exec().getResult());
                            device.setModel(new ModelCommand(device).exec().getResult());
                            device.setVersion(new VersionCommand(device).exec().getResult());
                            device.setSdkVersion(new SdkVersionCommand(device).exec().getResult());
                        }
                        deviceList.add(device);
                    } else {
                        Log.e(TAG, "unknown format: " + lines[i]);
                    }
                }
            }
        }
        return this;
    }

    @Override
    public boolean execResult() {
        return log.contains("List of devices attached");
    }

    public List<Device> getDeviceList() {
        return deviceList;
    }

    public boolean isGetDeviceInfo() {
        return getDeviceInfo;
    }

    public DevicesCommand setGetDeviceInfo(boolean getDeviceInfo) {
        this.getDeviceInfo = getDeviceInfo;
        return this;
    }
}
